/**
 * 菜单修改时，父菜单选择，需要去掉按钮
 * 因为按钮只能作为子级，不可以作为父级菜单
 * @param data
 * @returns {*}
 */
export function newTreeData(data) {
    const cloneData = JSON.parse(JSON.stringify(data))
    return selfLoopTree(cloneData)
}
export function selfLoopTree(data) {
    data.forEach((v, i, arr) => {
        if (v.menuType == 'F') {
            arr[i] = []
        } else {
            if (v.children && v.children.length > 0) {
                selfLoopTree(v.children)
            } else {
            }
        }
    })
    return data
}

/**
 * 通用js方法封装处理
 * Copyright (c)
 */

export function dateSub(str1, str2, frequency) {
    var date1 = new Date(str1)
    var date2 = new Date(str2)
    var s1 = date1.getTime(),
        s2 = date2.getTime()
    if (s1 < 0) return 0
    var total = parseInt((s2 - s1) / 1000)

    return Math.floor(total / frequency)
}
// 日期格式化
export function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time)
        } else if (typeof time === 'string') {
            time = time
                .replace(new RegExp(/-/gm), '/')
                .replace('T', ' ')
                .replace(new RegExp(/\.[\d]{3}/gm), '')
        }
        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}
// 表单重置
export function resetForm(refName) {
    if (this.$refs[refName]) {
        this.$refs[refName].resetFields()
    }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
    var search = params
    search.params = {}
    if (null != dateRange && '' != dateRange) {
        if (typeof propName === 'undefined') {
            search.params['beginTime'] = dateRange[0]
            search.params['endTime'] = dateRange[1]
        } else {
            search.params['begin' + propName] = dateRange[0]
            search.params['end' + propName] = dateRange[1]
        }
    }
    return search
}

// 回显数据字典
export function selectDictLabel(datas, value) {
    var actions = []
    Object.keys(datas).some((key) => {
        if (datas[key].dictValue == '' + value) {
            actions.push(datas[key].dictLabel)
            return true
        }
    })
    return actions.join('')
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
    var actions = []
    var currentSeparator = undefined === separator ? ',' : separator
    var temp = value.split(currentSeparator)
    Object.keys(value.split(currentSeparator)).some((val) => {
        Object.keys(datas).some((key) => {
            if (datas[key].dictValue == '' + temp[val]) {
                actions.push(datas[key].dictLabel + currentSeparator)
            }
        })
    })
    return actions.join('').substring(0, actions.join('').length - 1)
}

// 字符串格式化(%s )
export function sprintf(str) {
    var args = arguments,
        flag = true,
        i = 1
    str = str.replace(/%s/g, function () {
        var arg = args[i++]
        if (typeof arg === 'undefined') {
            flag = false
            return ''
        }
        return arg
    })
    return flag ? str : ''
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
    if (!str || str == 'undefined' || str == 'null') {
        return ''
    }
    return str
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree(data, id, parentId, children, rootId) {
    id = id || 'id'
    parentId = parentId || 'parentId'
    children = children || 'children'
    rootId =
        rootId ||
        Math.min.apply(
            Math,
            data.map((item) => {
                return item[parentId]
            })
        ) ||
        0
    //对源数据深度克隆
    const cloneData = JSON.parse(JSON.stringify(data))
    //循环所有项
    const treeData = cloneData.filter((father) => {
        let branchArr = cloneData.filter((child) => {
            //返回每一项的子级数组
            return father[id] === child[parentId]
        })
        branchArr.length > 0 ? (father.children = branchArr) : ''
        //返回第一层
        return father[parentId] === rootId
    })
    return treeData != '' ? treeData : data
}
export function deepCopy(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach((keys) => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepCopy(source[keys])
        } else {
            targetObj[keys] = source[keys]
        }
    })
    return targetObj
}

export function getRecent7Days() {
    const DAYS = 7
    let weeksday = []
    for (var i = 0; i < DAYS; i++) {
        var day = new Date().getTime() - 1000 * 3600 * 24 * i
        weeksday.push(dateFormat(new Date(day)).slice(0, 10))
    }
    return weeksday
}

export function theWeek() {
    var totalDays = 0
    let now = new Date()
    let years = now.getYear()
    if (years < 1000) years += 1900
    var days = new Array(12)
    days[0] = 31
    days[2] = 31
    days[3] = 30
    days[4] = 31
    days[5] = 30
    days[6] = 31
    days[7] = 31
    days[8] = 30
    days[9] = 31
    days[10] = 30
    days[11] = 31
    //判断是否为闰年，针对2月的天数进行计算
    if (Math.round(now.getYear() / 4) == now.getYear() / 4) {
        days[1] = 29
    } else {
        days[1] = 28
    }
    if (now.getMonth() == 0) {
        totalDays = totalDays + now.getDate()
    } else {
        var curMonth = now.getMonth()
        for (var count = 1; count <= curMonth; count++) {
            totalDays = totalDays + days[count - 1]
        }
        totalDays = totalDays + now.getDate()
    }
    //得到第几周
    var week = Math.round(totalDays / 7)
    return week
}

export function dateFormat(date) {
    var date = new Date(date)
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    var d = date.getDate()
    var h = date.getHours()
    var mi = date.getMinutes()
    var sec = date.getSeconds()
    m = m > 9 ? m : '0' + m
    d = d > 9 ? d : '0' + d
    h = h > 9 ? h : '0' + h
    mi = mi > 9 ? mi : '0' + mi
    sec = sec > 9 ? sec : '0' + sec
    return y + '-' + m + '-' + d + ' ' + h + ':' + mi + ':' + sec
}
export function dateFormatMs(date) {
    var date = new Date(date)
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    var d = date.getDate()
    var h = date.getHours()
    var mi = date.getMinutes()
    var sec = date.getSeconds()
    var ms = date.getMilliseconds()
    m = m > 9 ? m : '0' + m
    d = d > 9 ? d : '0' + d
    h = h > 9 ? h : '0' + h
    mi = mi > 9 ? mi : '0' + mi
    sec = sec > 9 ? sec : '0' + sec
    if (ms < 10) {
        ms = '00' + ms
    } else if (ms > 9 && ms < 100) {
        ms = '0' + ms
    }

    return y + '-' + m + '-' + d + ' ' + h + ':' + mi + ':' + sec + '.' + ms
}

export function addOrReduceDate(type, date, num) {
    var nowDate = null
    var strDate = ''
    num = parseInt(num) // 防止传入字符串报错
    var seperator1 = '-'
    var seperator2 = ':'
    if (date == '') {
        nowDate = new Date()
    } else {
        nowDate = new Date(date)
    }

    if (type === 'Y') {
        nowDate.setFullYear(nowDate.getFullYear() + num)
    }
    if (type === 'M') {
        nowDate.setMonth(nowDate.getMonth() + num)
    }
    if (type === 'D') {
        nowDate.setDate(nowDate.getDate() + num)
    }
    if (type === 'H') {
        nowDate.setHours(nowDate.getHours() + num)
    }
    if (type === 'I') {
        nowDate.setMinutes(nowDate.getMinutes() + num)
    }
    if (type === 'A') {
        nowDate.setFullYear(nowDate.getFullYear() + num)
        nowDate.setMonth(nowDate.getMonth() + num)
        nowDate.setDate(nowDate.getDate() + num)
    }
    var year = nowDate.getFullYear() // 年
    var month = nowDate.getMonth() + 1 // 月
    strDate = nowDate.getDate() //日
    var hours = nowDate.getHours() // 时
    var minutes = nowDate.getMinutes() // 分
    var seconds = nowDate.getSeconds() // 秒
    if (month >= 1 && month <= 9) {
        month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
    }
    if (hours >= 0 && hours <= 9) {
        hours = '0' + hours
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = '0' + minutes
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = '0' + seconds
    }
    var dateStr =
        year + seperator1 + month + seperator1 + strDate + ' ' + hours + seperator2 + minutes + seperator2 + seconds
    return dateStr
}

export function DateMinus(date1, date2) {
    //date1:小日期   date2:大日期
    let sdate = new Date(date1)
    let now = new Date(date2)
    let days = now.getTime() - sdate.getTime()
    let day = parseInt(days / (1000 * 60 * 60 * 24))
    return day
}

export function cloneArrayObj(data) {
    let _obj = JSON.stringify(data)
    return JSON.parse(_obj)
}

export function cloneObj(data, hash = new WeakMap()) {
    if (typeof data !== 'object' || data === null) {
        throw new TypeError('传入参数不是对象')
    }
    // 判断传入的待拷贝对象的引用是否存在于hash中
    if (hash.has(data)) {
        return hash.get(data)
    }
    let newData = {}
    const dataKeys = Object.keys(data)
    dataKeys.forEach((value) => {
        const currentDataValue = data[value]
        // 基本数据类型的值和函数直接赋值拷贝
        if (typeof currentDataValue !== 'object' || currentDataValue === null) {
            newData[value] = currentDataValue
        } else if (Array.isArray(currentDataValue)) {
            // 实现数组的深拷贝
            newData[value] = [...currentDataValue]
        } else if (currentDataValue instanceof Set) {
            // 实现set数据的深拷贝
            newData[value] = new Set([...currentDataValue])
        } else if (currentDataValue instanceof Map) {
            // 实现map数据的深拷贝
            newData[value] = new Map([...currentDataValue])
        } else {
            // 将这个待拷贝对象的引用存于hash中
            hash.set(data, data)
            // 普通对象则递归赋值
            newData[value] = cloneObj(currentDataValue, hash)
        }
    })
    return newData

    // var newobj = obj.constructor === Array ? [...obj] : {...obj};
    // if (typeof obj !== "object") {
    //   return obj;
    // } else {
    //   Reflect.ownKeys(newobj).forEach(i => {
    //     newobj[i] = typeof obj[i] === "object" ? cloneObj(obj[i]) : obj[i];
    //   });
    // }
    // return newobj;
    // let _obj = JSON.stringify(obj);
    //   return JSON.parse(_obj);
    // let o = null;
    // if( typeof obj === "object" ){
    //   if ( obj === null ) {
    //     o = null;
    //   }else if ( obj instanceof Array  ) {
    //     o = [];
    //     for (let i = 0; i < obj.length; i++) {
    //       o.push( cloneObj( obj[i] ) );  //**确保数组内的任何类型数据均能被正确的clone
    //     };
    //   }else{
    //     o = {}
    //     for ( let j in obj ) {
    //       o[j] = cloneObj( obj[j] )
    //     };
    //   }
    // }else{
    //   o = obj;
    // }
    // return o;
}

export function readTimeTicks(time) {
    if (time === 0) return ''
    var d = 0,
        h = 0,
        m = 0,
        s = 0
    d = parseInt(time / (24 * 3600 * 100))
    time = d > 0 ? time % (24 * 3600 * 100) : time
    h = parseInt(time / (3600 * 100))
    time = h > 0 ? time % (3600 * 100) : time
    m = parseInt(time / 6000)
    time = m > 0 ? time % 6000 : time
    s = parseInt(time / 100)
    time = s > 0 ? time % 100 : time

    if (h < 10) h = '0' + h
    if (m < 10) m = '0' + m
    if (s < 10) s = '0' + s
    if (d > 0) {
        d = d + '天 '
    } else {
        d = ''
    }
    return `${d}${h}小时 ${m}分 ${s}秒`
}
export function readTimeTicksByHour(time) {
    if (time === 0) return ''
    var d = 0,
        h = 0,
        m = 0,
        s = 0
    d = parseInt(time / (24 * 3600 * 100))
    time = d > 0 ? time % (24 * 3600 * 100) : time
    h = parseInt(time / (3600 * 100))
    time = h > 0 ? time % (3600 * 100) : time
    m = parseInt(time / 6000)
    time = m > 0 ? time % 6000 : time
    s = parseInt(time / 100)
    time = s > 0 ? time % 100 : time

    if (h < 10) h = '0' + h
    if (m < 10) m = '0' + m
    if (s < 10) s = '0' + s
    if (d > 0) {
        d = d + '天 '
    } else {
        d = ''
    }
    return `${d}${h}小时`
}
export function readTimeTicksByDay(time) {
    if (time === 0) return ''
    var d = 0
    d = Math.ceil(time / (24 * 3600 * 100))
    return d
}

export function bytesToSize(value) {
    if (value === 0) return '0 B'
    let k = 1024, // or 1024
        sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(value) / Math.log(k))
    return (value / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}

export function KbytesToSize(value) {
    if (value === 0) return '0 B'
    let k = 1024, // or 1024
        sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(value) / Math.log(k))
    if (i < 0) {
        i = 0
    }
    return (value / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}

export function MbytesToSize(value) {
    if (value === 0) return '0 MB'
    let k = 1024, // or 1024
        sizes = ['MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(value) / Math.log(k))
    if (i < 0) {
        i = 0
    }
    return (value / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}
